package com.xnyzc.lhy.didi.service.impl.synchronization;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.*;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.netty.NettyDriverOrderInfo;
import com.xnyzc.lhy.common.entity.netty.StriveCallbackParam;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EDispatchType;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.penum.push.EJPushConfigKey;
import com.xnyzc.lhy.common.penum.push.EPushCode;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.common.util.attestation.ConversionMap;
import com.xnyzc.lhy.common.util.retry.RetryUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.didi.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.didi.entity.param.order.OrderDetailParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.DriverSingleSynchronousParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.LocationSyncParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.MultiLocationSyncList;
import com.xnyzc.lhy.didi.entity.param.synchronization.MultiLocationSyncParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.RealtimeFeeSyncParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.StatusCallbackParam;
import com.xnyzc.lhy.didi.feign.amap.IAmapService;
import com.xnyzc.lhy.didi.feign.mq.IMqService;
import com.xnyzc.lhy.didi.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.didi.mapper.other.OaDUserMapper;
import com.xnyzc.lhy.didi.mq.MQProducer;
import com.xnyzc.lhy.didi.service.gps.IOaSysTrajectoryService;
import com.xnyzc.lhy.didi.service.synchronization.DataSynchronizationCorrelationService;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.gps.OaSysTrajectory;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.order.entity.system.OaSysDispatchLog;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.resource.entity.jpush.PushInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 数据同步相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-10-06
 */
@Slf4j
@Service
public class DataSynchronizationServiceImpl implements DataSynchronizationCorrelationService {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private IMqService iMqService;

    @Autowired
    private IAmapService iAmapService;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private IOaSysTrajectoryService iOaSysTrajectoryService;

    @Autowired
    private MQProducer producer;



    /**
     * 司机位置同步
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getLocationSync(LocationSyncParam param) {
        //|| StringUtils.isBlank(param.getOpen_oid()) 同城没有传的参数
        if (StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getDriver_id())
                || CheckUtil.objIsEmpty(param.getTimestampms()) || CheckUtil.objIsEmpty(param.getLat()) || CheckUtil.objIsEmpty(param.getLng())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.LOCATION_SYNC_API;
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = RequestMethodUtil.requestMethod(signParameter, url);
        if (CheckUtil.strIsNotEmpty(data)) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
                // 成功
            }
        } else {
            return DiDiRv.wrapError(EDiDiErrorCode.syncDriverLocationFail);
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
    }

    /**
     * 实时计价同步
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getRealtimeFeeSync(RealtimeFeeSyncParam param) {
        if (CheckUtil.objIsEmpty(param.getTotal_fee()) || StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.REALTIME_FEE_API;
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = RequestMethodUtil.requestMethod(signParameter, url);
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            // 成功
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
    }

    /**
     * 司机状态同步（含Retry重试）
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getStatusCallback(StatusCallbackParam param) {
        if (CheckUtil.objIsEmpty(param.getDriver_lat()) || CheckUtil.objIsEmpty(param.getDriver_lng()) || StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.STATUS_CALL_BACK_API;
        // ###########公共的，待抽出
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            if (param.getIsRetry() == null || !param.getIsRetry()) {
                data = RequestMethodUtil.requestMethod(signParameter, url);
                log.info("滴滴状态同步没有启用 Retry 重试机制，是否启用：{}", param.getIsRetry());
            } else {
                data = RetryUtil.retryRequestMethodUtil(signParameter, url, 6, 1000L, 1.0);
                log.info("滴滴状态同步启用 Retry 重试机制，是否启用：{}", param.getIsRetry());
            }
        } catch (Exception e) {
            log.info("调用滴滴状态同步接口失败！！Retry重试方法抛出异常" + e.getMessage());
        }
        if (CheckUtil.strIsEmpty(data)) {
            return DiDiRv.wrapErrorCode(EDiDiErrorCode.driverStatusSynFailed);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            log.info("ORDER_HISTORY 订单号:[{}], 司机状态同步,状态:[{}}],滴滴返回值:[{}],请求参数:[{}]", param.getOrder_id(), param.getStatus(), jsonObject, param);
            // 成功
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        }
        log.info("ORDER_HISTORY 订单号:[{}], 司机状态同步失败,状态:[{}}],滴滴返回值:[{}],请求参数:[{}]", param.getOrder_id(), param.getStatus(), jsonObject, param);
        return DiDiRv.wrapErrorCode(EDiDiErrorCode.driverStatusSynFailed);
    }

    /**
     * 司机抢单
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getStriveCallback(StriveCallbackParam param) {
        if (CheckUtil.objIsEmpty(param.getDriver_lat(), param.getDriver_lng())) {
            log.info("调用司机抢单接口参数问题1");
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        if (CheckUtil.strIsEmpty(param.getOrder_id(), param.getProduct_type(), param.getRide_type(), param.getDriver_id(),
                param.getDriver_phone(), param.getDriver_name(), param.getCar_brand(), param.getCar_plate_number(), param.getCar_color())) {
            log.info("调用司机抢单接口参数问题2");
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String cityId = param.getCityId();
        param.setCityId(null);
        try {
            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
            dispatchLog.setType(EDispatchType.grabOrdersBefore.getType());
            dispatchLog.setOrderId(param.getOrder_id());
            dispatchLog.setLogId(IDUtil.nextId());
            dispatchLog.setCityId(cityId);
            dispatchLog.setTimestamp(System.currentTimeMillis());
            producer.sendMsg(dispatchLog, EDispatchType.grabOrdersBefore.getDesc(), "LHY_EVENT");
//            iMqService.getDispatchLog(dispatchLog);
        } catch (Exception e) {
            log.error("记录订单调度日志!");
        }
        String carBrand = param.getCar_brand();
        String carBrandNew = carBrand.substring(0, carBrand.indexOf('·'));
        param.setCar_brand(carBrandNew);
        log.info("进入司机抢单接口");
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.STRIVE_CALL_BACK_API;
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        JSONObject jsonObject = null;
        try {
            log.info("调用前======http调用滴滴接口，访问地址为：{" + url + "}访问参数为：{" + signParameter + "}");
            String data = RetryUtil.retryRequestMethodUtil(signParameter, url, 3, 500L, 2.0);
            log.info("调用后======http调用滴滴接口返回成功，访问地址为：{" + url + "}返回为：{" + data + "}");
            jsonObject = JSONObject.parseObject(data);
        } catch (Exception e) {
            log.info("调用后======http调用滴滴接口 Exception，异常信息为" + e.getMessage());
        }
        if (CheckUtil.objIsEmpty(jsonObject) || CheckUtil.objIsEmpty(jsonObject.get(DiDiUrlConstant.ERRNO))) {
            // 访问不到按照else走
            log.info("调用滴滴司机抢单接口HTTP请求失败，返回值为" + jsonObject.toJSONString() + "准备释放司机运力");
            // 对redis中的数据进行删除key操作
            redisCleanOrderMsg(param.getOrder_id());
            // 修改订单状态
            iMqService.singleFailureStatus(param.getOrder_id());
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        Object errno = jsonObject.get(DiDiUrlConstant.ERRNO);
        try {
            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
            dispatchLog.setType(EDispatchType.grabOrdersAfter.getType());
            dispatchLog.setOrderId(param.getOrder_id());
            dispatchLog.setLogId(IDUtil.nextId());
            dispatchLog.setCityId(cityId);
            if (CheckUtil.objIsNotEmpty(errno)) {
                dispatchLog.setSyncResultCode(errno.toString());
            }
            dispatchLog.setTimestamp(System.currentTimeMillis());
            producer.sendMsg(dispatchLog, EDispatchType.grabOrdersAfter.getDesc(), "LHY_EVENT");
//            iMqService.getDispatchLog(dispatchLog);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("记录订单调度日志!");
        }
        //验证该司机
        // 抢单成功
        if (errno.equals(EDiDiErrorCode.success.getValue())) {
            // 进行一个异步回调，查看订单状态，防止滴滴司机抢单结果同步回调失败（5秒查一次，最长时限10秒）
            log.info("调用后======http调用滴滴接口成功，并且抢单成功，开始告诉司机接单");
            OrderDetailParam orderDetailParam = new OrderDetailParam();
            orderDetailParam.setOrder_id(param.getOrder_id());
            orderDetailParam.setOpen_oid(param.getOpen_oid());
            // 将MQ服务间调用更改为直发 --- hu
//            iMqService.getDidiSheet(orderDetailParam);
            producer.sendMsg(orderDetailParam, MqConstant.DIDI_GRAB_SHEET_TAG, null);
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            log.info("调用后======http调用滴滴接口成功，但是抢单失败，开始释放司机运力");
            // 对redis中的数据进行删除key操作
            redisCleanOrderMsg(param.getOrder_id());
            // 修改订单状态，统一订单被别人抢
            iMqService.singleFailureStatus(param.getOrder_id());
        }

        return DiDiRv.wrapSuccess(EDiDiErrorCode.getStriveCallbackFail);
    }

    /**
     * 司机抢单结果同步
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv driverSingleSynchronous(DriverSingleSynchronousParam param) {
        if (StringUtils.isBlank(param.getStrive_status()) || StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        log.info("被滴滴调用======司机抢单结果同步被调用了");
        String securityKey = RedisPrefixConstant.DIDI_GRAB_SHEET_RESULT + param.getOrder_id();
        // 安全机制防止异步错误
        if (redisCommon.hashKey(securityKey)) {
            log.info("被滴滴调用======滴滴抢单结果回调被调用了，我来删除Redis的回调信息，并return");
            redisCommon.remove(securityKey);
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            // 通知mq得到结果
            log.info("被滴滴调用======滴滴抢单结果回调没有被调用，告诉大家我调用了，继续下面操作");
            redisCommon.set(securityKey, "true", 15);
        }

        try {
            QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(OaCOrderPersonal.CITY_ID);
            queryWrapper.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
            List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(queryWrapper);
            OaCOrderPersonal orderPersonal = oaCOrderPersonals.get(0);
            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
            dispatchLog.setType(EDispatchType.orderSynchronize.getType());
            dispatchLog.setOrderId(param.getOrder_id());
            dispatchLog.setAsyncNoticeGrapResult(Integer.valueOf(param.getStrive_status()));
            dispatchLog.setLogId(IDUtil.nextId());
            dispatchLog.setTimestamp(System.currentTimeMillis());
            if (CheckUtil.objIsEmpty(orderPersonal)) {
                dispatchLog.setCityId(orderPersonal.getCityId());
            }
            producer.sendMsg(dispatchLog, EDispatchType.orderSynchronize.getDesc(), "LHY_EVENT");
//            iMqService.getDispatchLog(dispatchLog);
        } catch (Exception e) {
            log.error("记录订单调度日志!");
        }
        // 成功
        if (StringUtils.equals(param.getStrive_status(), "1")) {
            log.info("被滴滴调用======司机抢单结果同步，回调抢单成功");
            // 查询订单信息
            OaCOrderPersonal oaCOrderPersonal = iMqService.billDetails(param.getOrder_id());
            Long driverId = oaCOrderPersonal.getDriverId();
            log.info("获取到的司机driverId为：{}，订单号为：{}", driverId, oaCOrderPersonal.getOrderNo());
            //获取司机订单暂存信息
            String str = redisCommon.getStr(String.format("%s%s", RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE, oaCOrderPersonal.getOrderNo()));
            if (CheckUtil.strIsNotEmpty(str)) {
                log.info("准备开始给司机推送，判断是等待应答的订单才给推送！");
                // 判断是等待应答的订单才给推送
                if (StringUtils.equals(oaCOrderPersonal.getDidiOrderStatus().toString(), EDiDiOrderStatus.waitingResponse.getDidiType().toString())) {
                    log.info("是等待应答的订单！");
                    Date dateTime = new Date();
                    NettyDriverOrderInfo nettyDriverOrderInfo = JSON.parseObject(str, NettyDriverOrderInfo.class);
                    // 修改订单表数据
                    oaCOrderPersonal.setPassengerPhone(param.getPassenger_phone());
                    oaCOrderPersonal.setPassengerPhoneSuffix(param.getPassenger_phone_suffix());
                    oaCOrderPersonal.setOrderStatus(EDiDiOrderStatus.driverOrder.getType());
                    oaCOrderPersonal.setDidiOrderStatus(EDiDiOrderStatus.driverOrder.getDidiType());
                    oaCOrderPersonal.setGpsId(nettyDriverOrderInfo.getGpsId().intValue());
                    oaCOrderPersonal.setMeetPassengerTime(dateTime);
                    // 获取uploadId
                    try {
                        String savePath = oaCOrderPersonal.getOrderNo() + ".mp3";
                        String uploadId = iAmapService.getUploadId(savePath);
                        uploadId = uploadId.replaceAll("\"", "");
                        oaCOrderPersonal.setUploadId(uploadId);
                    } catch (Exception e) {
                        log.info("获取uploadId失败，报错信息为{}", e.getMessage());
                    }
                    oaCOrderPersonal.setUserId("0");
                    int updateById = oaCOrderPersonalMapper.updateById(oaCOrderPersonal);
                    if (updateById < 1) {
                        log.error("修改订单信息失败，订单号为：{}，司机ID为：{}", oaCOrderPersonal.getOrderNo(), driverId);
                        throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
                    }else{
                        //司机抢单成功并接单日志放到mq


                    }

                    //获取gpsId
                    // 司机接单表添加数据
                    OaDOrder oaDOrder = new OaDOrder();
                    // 获取司机接单位置
                    String gpsStr = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + driverId);
                    if (CheckUtil.strIsNotEmpty(gpsStr)) {
                        OaDVehicleGps oaDVehicleGps = JSON.parseObject(gpsStr, OaDVehicleGps.class);
                        String lng = oaDVehicleGps.getLng();
                        String lat = oaDVehicleGps.getLat();

                        // 同步滴滴司机位置
                        LocationSyncParam locationSyncParam = new LocationSyncParam();
                        locationSyncParam.setOpen_oid(param.getOpen_oid());
                        locationSyncParam.setOrder_id(param.getOrder_id());
                        locationSyncParam.setDriver_id(oaDVehicleGps.getDriverId().toString());
                        Date date = new Date();
                        long timestampms = date.getTime();
                        locationSyncParam.setTimestampms(timestampms);
                        locationSyncParam.setLat(new BigDecimal(lat));
                        locationSyncParam.setLng(new BigDecimal(lng));
                        getLocationSync(locationSyncParam);

                        oaDOrder.setPickPassengersFlng(lng);
                        oaDOrder.setPickPassengersFlat(lat);
                        log.info("司机开始接单======开始地址的逆地理编码，我准备开始获取了");
                        String regeo = iAmapService.getRegeo(lng + "," + lat);
                        log.info("司机开始接单======我调用成功了，数据为：" + regeo);
                        regeo = regeo.replaceAll("\"", "");
                        if (CheckUtil.strIsEmpty(regeo)) {
                            log.info("调用地址逆编码为空！！！继续接单");
                        } else {
                            log.info("调用地址逆编码为不为空！！！继续接单");
                            oaDOrder.setPickPassengersAddress(regeo);
                        }
                    }
                    oaDOrder.setOrderNo(param.getOrder_id());
                    oaDOrder.setDriverId(Long.valueOf(driverId));
                    // 司机接单时间
                    oaDOrder.setStriveTime(dateTime);
                    oaDOrder.setUserOrderId(oaCOrderPersonal.getPersonalId() + "");
                    oaDOrder.setUpdateTime(dateTime);
                    oaDOrder.setUpdateUser(1L);
                    oaDOrder.setCreateTime(dateTime);
                    oaDOrder.setCreateUser(1L);
                    oaDOrder.setPassengerPhone(param.getPassenger_phone());
                    oaDOrder.setFlat(oaCOrderPersonal.getStartLat());
                    oaDOrder.setFlng(oaCOrderPersonal.getStartLng());
                    oaDOrder.setTlat(oaCOrderPersonal.getEndLat());
                    oaDOrder.setTlng(oaCOrderPersonal.getEndLng());
                    oaDOrder.setOrderStatus(EDiDiOrderStatus.driverOrder.getType());
                    oaDOrder.setVehicleId(Long.valueOf(oaCOrderPersonal.getVehicleId()));
                    log.info("被滴滴调用======我要开始添加司机接单表的信息，准备完毕");
                    Boolean aBoolean = iMqService.addDriverOrderInfo(oaDOrder);
                    if (!aBoolean) {
                        throw DiDiException.create(EDiDiErrorCode.driverOrderCreateFail);
                    }
                    log.info("被滴滴调用======成功添加司机接单表的信息");
                    redisCommon.set(RedisPrefixConstant.ORDER_OA_D_ORDER + oaCOrderPersonal.getOrderNo(), JSON.toJSONString(oaCOrderPersonal));
                    nettyDriverOrderInfo.setPhone(param.getPassenger_phone());
                    nettyDriverOrderInfo.setTailNumber(param.getPassenger_phone_suffix());
                    //获取token
                    HashMap tokenUserKey = redisCommon.getHashMap("tokenUserKey");
                    if (CheckUtil.mapIsEmpty(tokenUserKey)) {
                        log.info("无法获取到token列表!");
                    } else {
                        // 获取司机最新的token
                        String driverTokenKey = driverId + ":Driver";
                        Object redisDriverToken = tokenUserKey.get(driverTokenKey);
                        if (CheckUtil.objIsEmpty(redisDriverToken)) {
                            log.info("未获取用户token,无法继续进行!,redis_key: {},redis_token: {}", driverTokenKey, redisDriverToken);
                        } else {
                            nettyDriverOrderInfo.setDriverToken(redisDriverToken.toString());
                        }
                    }
                    // redis添加数据等待司机接单
                    redisCommon.set(String.format("%s%s", RedisPrefixConstant.ORDER_VEH, driverId), JSON.toJSONString(nettyDriverOrderInfo));
                    // 给司机发送短信进行强通知
                    String driverPhone = iMqService.getDriverPhone(driverId.toString()).replaceAll("\"", "");
                    //QCloudSMSUtils.sendMessage(driverPhone, QCloudSmsConstant.DRIVER_ORDER_MSG, (ArrayList<String>) null);
                    AliCloudSMSUtils.sendMessage(driverPhone, AliCloudSmsConstant.DRIVER_ORDER_MSG, null);
                    // 给司机推送消息进行强通知
                    driverPushMessage(driverPhone);

                    // 存入预估轨迹
                    String estimateKey = RedisPrefixConstant.DIDI_ESTIMATE + oaCOrderPersonal.getEstimateId();
                    HashMap<String, Object> hashMap = redisCommon.getHashMap(estimateKey);
                    String polyStr = hashMap.get(EGould.gouldPolyline.getValue()).toString();
                    if (CheckUtil.strIsEmpty(polyStr)) {
                        log.error("创建订单时，Redis预估轨迹获取失败！参数为{" + polyStr + "}");
                    }
                    String[] splitPolyList = polyStr.split(";");
                    if (splitPolyList.length < 1) {
                        log.error("创建订单时，Redis预估轨迹格式错误！参数为{" + splitPolyList.toString() + "}");
                    }
                    List<OaSysTrajectory> trajectoryList = new ArrayList<>();
                    for (String splitPoly : splitPolyList) {
                        String[] splitList = splitPoly.split(",");
                        if (splitList.length < 2) {
                            log.error("创建订单时，Redis预估轨迹经纬度不是成对的！参数为{" + splitList.toString() + "}");
                        }
                        OaSysTrajectory oaSysTrajectory = new OaSysTrajectory();
                        long id = IDUtil.nextId();
                        oaSysTrajectory.setTrajectoryId(id);
                        oaSysTrajectory.setOrderNo(param.getOrder_id());
                        oaSysTrajectory.setLng(splitList[0]);
                        oaSysTrajectory.setLat(splitList[1]);
                        oaSysTrajectory.setCreateTime(dateTime);
                        oaSysTrajectory.setCreateUser(oaCOrderPersonal.getDidiUserId());
                        trajectoryList.add(oaSysTrajectory);
                    }

                    iOaSysTrajectoryService.saveBatch(trajectoryList);

                }
            } else {
                log.error("获取司机订单暂存信息为空：{}，订单号为：{}", str, param.getOrder_id());
            }
        } else {
            // 失败
            log.info("被滴滴调用======司机抢单结果同步，回调抢单失败,尝试取消订单");
            redisCleanOrderMsg(param.getOrder_id());
            // 修改订单状态，统一订单被别人抢
            iMqService.singleFailureStatus(param.getOrder_id());
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
    }

    public void driverPushMessage(String driverPhone) {
        List<String> aliasList = new ArrayList<>();
        aliasList.add(driverPhone);
        JSONObject jsonObject = new JSONObject();
        JSONObject result = new JSONObject();
        result.put("title", MessageConstant.ORDER_INFORM);
        jsonObject.put("expand", JSON.toJSONString(result));
        PushInfoEntity pushInfoEntity = new PushInfoEntity();
        pushInfoEntity.setPushCode(EPushCode.driverOrderInform.getValue());
        pushInfoEntity.setPhones(aliasList);
        pushInfoEntity.setExtras(jsonObject);
        pushInfoEntity.setContent(MessageConstant.RECEIVED_ORDER_INFORM);
        pushInfoEntity.setTag("lhy");
        pushInfoEntity.setClientId(EJPushConfigKey.driver.getValue());
        pushInfoEntity.setJudgeCms("DRIVER");
        pushInfoEntity.setTitle(MessageConstant.ORDER_INFORM);
        pushInfoEntity.setPushLink("");
        iAmapService.pushMessage(pushInfoEntity);
    }

    private void redisCleanOrderMsg(String order_id) {
        String orderNo = order_id;
        String key = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
        String keyVeh = RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE + orderNo;
        redisCommon.remove(keyVeh);
        redisCommon.remove(key);
    }

    /**
     * 司机位置批量同步
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getMultiLocationSync(MultiLocationSyncParam param) {
        if (StringUtils.isBlank(param.getSign())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.MULTI_LOCATION_SYNC_API + "?case_id=1&sandbox_token=n5lIMf20G4KdHJzWPc8J0XN2juqlt4K2sEEGnUNdMOJcwWGYUJaEK1l3jdPBZjjT";
        param.setTimestamp(String.valueOf(System.currentTimeMillis()));
        param.setApp_id(DiDiUrlConstant.didiAppId);

        List<MultiLocationSyncList> syncList = JSONObject.parseArray(param.getMulti_location(), MultiLocationSyncList.class);
        MultiLocationSyncList sync = syncList.get(0);
        Map<String, Object> resMap = new HashMap<>();
        try {
            resMap = ConversionMap.beanToMap(sync);
        } catch (IllegalAccessException e) {
        }
        String mapString = "";
        String a = "multi_location[0][aaa]";
        for (Object key : resMap.keySet()) {
            String b = a.replace("aaa", key.toString());
            mapString = mapString + b + "=" + resMap.get(key) + "&";
        }
        mapString = mapString.substring(0, mapString.length() - 1);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        signParameter = signParameter + "&" + mapString;
        //String signParameter="sign=str&timestamp=str&app_id=1010&multi_location[0][timestampms]=1&multi_location[0][lng]=1.1&multi_location[0][lat]=1.1&multi_location[0][speed]=1.1&multi_location[0][direction]=1.1&multi_location[0][altitude]=1.1&multi_location[0][air_pressure]=1.1&multi_location[0][loc_type]=1&multi_location[0][accuracy]=1&multi_location[0][open_oid]=str&multi_location[0][order_id]=str&multi_location[0][status]=str&multi_location[0][driver_id]=str&multi_location[0][driver_status]=str";
        String data = RequestMethodUtil.requestMethod(signParameter, url);
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            // 成功
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
    }

}
